package net.xuele.learn.highConcurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by GaoQingming on 2019/4/10 0010.
 */
public class CountLatchUtil {
    private CountDownLatch start;
    private CountDownLatch end;
    private int poolSize = 10;

    public CountLatchUtil() {
        this(10);
    }

    public CountLatchUtil(int poolSize) {
        this.poolSize = poolSize;
        start = new CountDownLatch(1);
        end = new CountDownLatch(poolSize);
    }


    public void latch (MyFunctionalInterface myFunctionalInterface) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < poolSize; i++) {
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            start.await();
                            myFunctionalInterface.run();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            end.countDown();
                        }
                    }
                };
                executorService.submit(r);
        }
        start.countDown();
        end.await();
        executorService.shutdown();
    }

    @FunctionalInterface
    public interface MyFunctionalInterface{
        void run();
    }
}
